In [1]:
from collections import deque
dq = deque()
dq.append(1)
dq.append(2)
dq.appendleft(3)
dq
Out[1]:
In [2]:
v = dq.pop()
v
Out[2]:
In [3]:
dq.popleft()
Out[3]:
In [4]:
dq
Out[4]:
Using maxlen to limit the num of items in a deque
In [5]:
dq = deque(maxlen = 3)
for n in range(10):
dq.append(n)
dq
Out[5]:
heapq provides O(1) access to the smallest item in the heap.
In [11]:
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
In [12]:
#heapq is created from a list
heap = list(nums)
heapq.heapify(heap)
#now the 1st element is guarenteed to be the smallest
heap
Out[12]:
In [13]:
heapq.heappop(heap)
Out[13]:
In [14]:
heap
Out[14]:
In [15]:
heapq.heappush(heap, -10)
heap
Out[15]:
nlargest / nsmallest wraps creation of a heap for one-time access
In [16]:
# nlargest and nsmallest wrap a heapq to provide its results
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
In [17]:
# providing an alternate sort key to nlargest/nsmallest
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
Out[17]:
In [1]:
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words) #Works with any hashable items, not just strings!
word_counts.most_common(3)
Out[1]:
In [4]:
morewords = ['why','are','you','not','looking','in','my','eyes']
for word in morewords:
word_counts[word] += 1
word_counts.most_common(3)
Out[4]:
In [5]:
evenmorewords = ['seriously','look','into','them','while','i','look','at', 'you']
word_counts.update(evenmorewords)
word_counts.most_common(3)
Out[5]:
In [6]:
a = Counter(words)
b = Counter(morewords)
c = Counter(evenmorewords)
In [7]:
# combine counters
d = b + c
d
Out[7]:
In [8]:
# subtract counts
e = a-d
e
Out[8]:
In [ ]: